import json
import time
from datetime import datetime
from urllib.request import urlretrieve


with open('coinfo_anno.json', 'r', encoding='utf-8') as f:
    announcements = json.load(f)


def pdf_url(bid, ts):
    t = datetime.fromtimestamp(ts//1000)
    t = t.strftime('%Y-%m-%d')
    return f'http://www.cninfo.com.cn/new/announcement/download?bulletinId={bid}&announceTime={t}'


for i in range(len(announcements)):
    if i > 2:
        break
    anno = announcements[i]
    url = pdf_url(anno['announcementId'], anno['announcementTime'])
    print(f'Downloading {anno["announcementId"]}-{anno["announcementTitle"]}.pdf')
    try:
        urlretrieve(url, f'cninfo_pdf/{anno["announcementId"]}-{anno["announcementTitle"]}.pdf')
    except Exception as e:
        print(e)
        with open('cninfo_errors.txt', 'w') as f:
            f.write(f'{anno["announcementId"]}\n')
    time.sleep(2)
